<template>

    <!-- 固钉组件，通过设置 offset 属性来改变吸顶距离，默认值为 0。 -->
    <el-affix :offset="0">
        <!-- 设置背景色为白色、高度为 64px，padding-right 为 4， border-bottom 为 slate 100 -->
        <div class="bg-white h-[64px] flex pr-4 border-b border-slate-200">
            <!-- 左边栏收缩、展开 -->
            <div class="w-[42px] h-[64px] cursor-pointer flex items-center justify-center text-gray-700 hover:bg-gray-200"
                @click="handleMenuWidth">
                <!-- tooltip 鼠标悬浮提示 -->
                <el-tooltip :content="menuStore.menuWidth === '250px' ? '收起' : '展开'" effect="customized">
                    <!-- icon 中进行判断 根据宽度选择icon图标 -->
                    <el-icon>
                        <Fold v-if="menuStore.menuWidth === '250px'" />
                        <Expand v-else />
                    </el-icon>
                </el-tooltip>
            </div>

            <!-- 右边容器，通过 ml-auto 让其在父容器的右边 -->
            <div class="ml-auto flex items-center">
                <!-- 点击全屏展示 -->

                <!-- tooltip 鼠标悬浮提示 -->
                <el-tooltip content="全屏" effect="customized">
                    <div class="w-[42px] h-[64px] cursor-pointer flex items-center justify-center text-gray-700 mr-2 hover:bg-gray-200"
                        @click="toggle">
                        <el-icon>
                            <FullScreen v-if="!isFullscreen" />
                            <Aim v-else />
                        </el-icon>
                    </div>
                </el-tooltip>
                <!-- 点击跳转前台首页 -->
                <el-tooltip class="box-item" effect="dark" content="跳转前台" placement="bottom">
                    <div class="w-[42px] h-[64px] cursor-pointer flex items-center justify-center text-gray-700 hover:bg-gray-200"
                        @click="router.push('/')">
                        <el-icon>
                            <Monitor />
                        </el-icon>
                    </div>
                </el-tooltip>

                <!-- 登录用户头像 -->
                <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link flex items-center justify-center text-gray-700 text-xs">
                        <el-avatar class="mr-2" :size="25"
                            :src="userStore.userInfo.avatar" />
                        {{ userStore.userInfo.username }}
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
                            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <!-- 修改密码的对话框 -->
            <FormDialog ref="dialogVisible" @submit="onSubmit" title="修改密码" destroyOnClose>
                <el-form ref="formRef" :rules="rules" :model="form">
                    <el-form-item label="用户名" prop="username" label-width="120px">

                        <el-input size="large" v-model="form.username" placeholder="请输入用户名" clearable disabled />
                    </el-form-item>
                    <el-form-item label="密码" prop="password" label-width="120px">
                        <el-input size="large" type="password" v-model="form.password" placeholder="请输入密码" clearable
                            show-password />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePassword" label-width="120px">
                        <el-input size="large" type="password" v-model="form.rePassword" placeholder="请确认密码" clearable
                            show-password />
                    </el-form-item>
                </el-form>
            </FormDialog>

        </div>
    </el-affix>

</template>

<script setup>
import { Fold, FullScreen, ArrowDown } from '@element-plus/icons-vue'
import { useMenuStore } from '@/stores/menu'; //全局状态
import { useFullscreen } from '@vueuse/core' //全屏展示
import { showModel, showMessage } from '@/composables/utils' //消息弹出框
import { useUserStore } from '@/stores/user'//获取用户的全局状态
import { useRouter } from 'vue-router' //路由
import { ref, reactive, watch } from 'vue'
import { updateAdminPassword } from '@/api/admin/user'
import FormDialog from '@/components/FormDialog.vue'

// 引入了菜单 store
const menuStore = useMenuStore();
// 引入了全屏展示
const { isFullscreen, toggle } = useFullscreen()

// icon 点击事件
const handleMenuWidth = () => {
    try {
        menuStore.handleMenuWidth()
    } catch (error) {
        console.error('菜单宽度切换失败:', error)
    }
}

// 拿到用户的信息
const userStore = useUserStore()
const router = useRouter()

// 通过 ref 接受组件 FormDialog 向外暴漏的参数 默认值是null
const dialogVisible = ref(null)
// 表单引用
const formRef = ref(null)

// 修改用户密码表单对象
const form = reactive({
    username: userStore.userInfo.username || '',
    password: '',
    rePassword: ''
})

// 下拉菜单事件处理
const handleCommand = (command) => {
    if (command === 'updatePassword') {
        dialogVisible.value.open()

    } else if (command === 'logout') {
        logout()
    }
}

// 退出登录
const logout = async () => {
    try {
        const confirm = await showModel('是否确认要退出登录？')
        if (confirm) {
            userStore.logout()
            showMessage('退出登录成功！')
            router.push('/login')
        }
    } catch (error) {
        console.error('退出登录失败:', error)
    }
}

// 监听 Pinia store 中的某个值的变化
watch(() => userStore.userInfo.username, (newValue, oldValue) => {
    console.log('新值:', newValue);
    console.log('旧值:', oldValue);
    form.username = newValue
}, { immediate: true })

const onSubmit = () => {
    if (form.password !== form.rePassword) {
        showMessage('两次密码输入不一致，请检查！', 'warning')
        return
    }

    //开启组件的加载动画
    dialogVisible.value.showBtnLoading()
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log('表单验证不通过')
            return false
        }

        updateAdminPassword(form).then((res) => {
            if (res.success) {
                showMessage('密码重置成功，请重新登录！')
                userStore.logout()
                dialogVisible.value.close()
                router.push('/login')
            } else {
                showMessage(res.message || '密码重置失败', 'error')
            }
        })
            .finally(() => {
                //关闭组件的加载动画
                dialogVisible.value.closeBtnLoading()
            })
            .catch(error => {
                console.error('API调用失败:', error)
                showMessage('服务器错误，请稍后再试', 'error')
            })
    })
}

// 规则校验
const rules = {
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' }
    ],
    rePassword: [
        { required: true, message: '确认密码不能为空', trigger: 'blur' }
    ]
}
</script>

<style>
.el-popper.is-customized {
    /* Set padding to ensure the height is 32px */
    padding: 6px 12px;
    background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
    background: linear-gradient(45deg, #b2e68d, #bce689);
    right: 0;
}
</style>